<?php
	abstract class SDBManager
	{
		protected $_sdb;
		protected $_domain;
		protected $_object_type;

		public function __construct($domain, $object_type)
		{
			$this->_sdb = Zend_Registry::get('sdb');
			$this->_domain = $domain;
			$this->_object_type = $object_type;
		}
		
		public function __destruct() 
		{ 
			unset($this->_sdb);
			unset($this->_domain);
			unset($this->_object_type);
		}
		
		# returns an array of objects
		public function query($query, $max_items = null)
		{
			$object_array = array();

			if (isset($max_items))
				$response = $this->_sdb->query($this->_domain, $query, $max_items);
			else
				$response = $this->_sdb->query($this->_domain, $query);

			if ($response->isSetQueryResult()) 
			{ 
				$items = $response->getQueryResult()->getItemName();

				foreach ($items as $item) 
				{ 
					$object = $this->objectConstructor();
					$object->load($item);
					$object_array[] = $object;
				} 
			}
			
			return $object_array;
		}

		# returns an array of objects
		public function getByFieldValue($field, $value)
		{
			$object_array = array();
			$query = "['$field' = '$value']";
			$response = $this->_sdb->query($this->_domain, $query);

			if ($response->isSetQueryResult()) 
			{
				$query_result = $response->getQueryResult();
				$items = $query_result->getItemName();

				foreach ($items as $item) 
				{ 
					$object = $this->objectConstructor();
					$object->load($item);
					$object_array[] = $object;
				} 
			}

			return $object_array;
		}

		# returns a bool
		public function isUniqueFieldValue($field, $value)
		{
			$exists = false;
			$query = "['$field' = '$value']";
			$response = $this->_sdb->query($this->_domain, $query);
			
			if ($response->isSetQueryResult()) 
			{
				$query_result = $response->getQueryResult();
				$items = $query_result->getItemName();
			}

			if (sizeof($items) == 0)
				$exists = true;

			return $exists;
		}
		
		# get domain
		public function getDomain()
		{
			return $this->_domain;
		}

		# get object type
		public function getObjectType()
		{
			return $this->_object_type;
		}
		
		# creates an instance of the model for the current database
		protected function objectConstructor()
		{
			$constructor = create_function('', "return new {$this->_object_type}();");
			return $constructor();
		}
	}
